/**
 * 本地Mermaid资源管理
 * 提供离线的Mermaid支持
 */

import { promises as fs } from 'fs';
import * as path from 'path';
import { createChildLogger } from '../../utils/logger.js';

export class LocalMermaidManager {
  private static log = createChildLogger('convert/mermaid-local');
  private static _mermaidScript: string | null = null;

  /**
   * 获取本地Mermaid脚本内容
   */
  static async getMermaidScript(): Promise<string> {
    if (this._mermaidScript) {
      return this._mermaidScript;
    }

    try {
      const mermaidPath = path.join(__dirname, 'assets', 'mermaid.min.js');
      this._mermaidScript = await fs.readFile(mermaidPath, 'utf8');
      return this._mermaidScript;
    } catch (error) {
      this.log.warn('⚠️ 无法加载本地Mermaid库，将使用备用方案');
      return this.getFallbackMermaidScript();
    }
  }

  /**
   * 备用的简化Mermaid处理脚本
   */
  private static getFallbackMermaidScript(): string {
    return `
      // 备用Mermaid处理器
      window.mermaidFallback = true;
      console.log('使用Mermaid备用处理器');
      
      // 简单的图表类型识别
      function getMermaidType(content) {
        const lines = content.trim().split('\\n');
        if (lines.length === 0) return 'empty';
        
        const firstLine = lines[0].trim().toLowerCase();
        if (firstLine.startsWith('graph')) return 'graph';
        if (firstLine.startsWith('flowchart')) return 'flowchart';
        if (firstLine.startsWith('sequencediagram')) return 'sequence';
        if (firstLine.startsWith('classDiagram')) return 'class';
        if (firstLine.startsWith('gantt')) return 'gantt';
        if (firstLine.startsWith('pie')) return 'pie';
        
        return 'unknown';
      }
      
      // 创建备用显示
      function createFallbackDisplay(content, type) {
        return '<div style="' +
          'padding: 15px; ' +
          'background: #e3f2fd; ' +
          'border: 2px solid #2196f3; ' +
          'border-radius: 6px; ' +
          'margin: 10px 0; ' +
          'font-family: monospace; ' +
          '\">' +
            '<div style="color: #1565c0; font-weight: bold; margin-bottom: 8px;">' +
              '📊 Mermaid图表 (' + type + ')' +
            '</div>' +
            '<div style="color: #1565c0; font-size: 12px; margin-bottom: 8px;">' +
              '离线模式：无法渲染图表，显示原始内容' +
            '</div>' +
            '<pre style="' +
              'background: #f8f9fa; ' +
              'padding: 10px; ' +
              'border-radius: 4px; ' +
              'font-size: 12px; ' +
              'line-height: 1.4; ' +
              'overflow-x: auto; ' +
              'white-space: pre-wrap; ' +
              'color: #333; ' +
              'border: 1px solid #ddd; ' +
            '">' + content + '</pre>' +
          '</div>';
      }
      
      // 触发就绪事件
      setTimeout(() => {
        window.dispatchEvent(new Event('mermaidReady'));
      }, 100);
    `;
  }

  /**
   * 生成包含Mermaid的HTML脚本
   */
  static async generateMermaidScript(
    theme: string = 'default',
    fontFamily: string = 'Arial'
  ): Promise<string> {
    const mermaidContent = await this.getMermaidScript();
    const isFallback = !this._mermaidScript;

    if (isFallback) {
      return `
        <script>
          ${mermaidContent}
        </script>
        <script>
          // 备用模式的元素处理
          document.addEventListener('DOMContentLoaded', () => {
            const mermaidElements = document.querySelectorAll('.mermaid');
            mermaidElements.forEach((element, i) => {
              const content = element.textContent || '';
              if (!content.trim()) {
                element.innerHTML = '<div style="padding: 10px; background: #f0f0f0; border: 1px dashed #ccc; text-align: center; color: #666;">📊 空的图表定义</div>';
                return;
              }
              
              const type = getMermaidType(content);
              element.innerHTML = createFallbackDisplay(content, type);
            });
          });
        </script>
      `;
    }

    return `
      <script>
        ${mermaidContent}
        
        // 初始化Mermaid
        try {
          if (typeof mermaid !== 'undefined') {
            mermaid.initialize({
              startOnLoad: false,
              theme: '${theme}',
              fontFamily: '${fontFamily}',
              fontSize: 14,
              securityLevel: 'loose',
              maxTextSize: 50000,
              logLevel: 'error'
            });
            
            console.log('✅ 本地Mermaid库加载成功');
            
            // 处理所有Mermaid元素
            document.addEventListener('DOMContentLoaded', async () => {
              const mermaidElements = document.querySelectorAll('.mermaid');
              
              for (let i = 0; i < mermaidElements.length; i++) {
                const element = mermaidElements[i];
                const graphDefinition = element.textContent;
                
                if (!graphDefinition || !graphDefinition.trim()) {
                  element.innerHTML = '<div style="padding: 10px; background: #f0f0f0; border: 1px dashed #ccc; text-align: center; color: #666;">📊 空的图表定义</div>';
                  continue;
                }
                
                try {
                  const { svg } = await mermaid.render('mermaid-' + i, graphDefinition);
                  element.innerHTML = svg;
                  console.log('✅ Mermaid图表 ' + (i + 1) + ' 渲染成功');
                } catch (error) {
                  console.warn('⚠️ Mermaid图表 ' + (i + 1) + ' 渲染失败:', error.message);
                  
                  const errorHtml = '<div style="' +
                    'padding: 15px;' +
                    'background: #fff3cd;' +
                    'border: 2px solid #ffc107;' +
                    'border-radius: 4px;' +
                    'margin: 10px 0;' +
                    '">' +
                      '<div style="color: #856404; font-weight: bold; margin-bottom: 8px;">' +
                        '📊 Mermaid图表渲染失败' +
                      '</div>' +
                      '<div style="color: #856404; font-size: 12px; margin-bottom: 8px;">' +
                        '错误信息: ' + error.message +
                      '</div>' +
                      '<details style="margin-top: 8px;">' +
                        '<summary style="color: #856404; cursor: pointer; font-size: 12px;">查看原始代码</summary>' +
                        '<pre style="background: #f8f9fa; padding: 8px; margin: 4px 0; border-radius: 2px; font-size: 11px; overflow-x: auto; white-space: pre-wrap;">' + graphDefinition + '</pre>' +
                      '</details>' +
                    '</div>';
                  element.innerHTML = errorHtml;
                }
              }
            });
            
          } else {
            throw new Error('Mermaid未正确加载');
          }
        } catch (error) {
          console.error('❌ Mermaid初始化失败:', error);
          
          // 使用备用显示
          document.addEventListener('DOMContentLoaded', () => {
            const mermaidElements = document.querySelectorAll('.mermaid');
            mermaidElements.forEach((element, i) => {
              const content = element.textContent || '';
              if (!content.trim()) {
                element.innerHTML = '<div style="padding: 10px; background: #f0f0f0; border: 1px dashed #ccc; text-align: center; color: #666;">📊 空的图表定义</div>';
                return;
              }
              
              const errorHtml = '<div style="' +
                'padding: 15px;' +
                'background: #ffebee;' +
                'border: 2px solid #f44336;' +
                'border-radius: 4px;' +
                'margin: 10px 0;' +
                '">' +
                  '<div style="color: #c62828; font-weight: bold; margin-bottom: 8px;">' +
                    '📊 Mermaid库加载失败' +
                  '</div>' +
                  '<div style="color: #c62828; font-size: 12px; margin-bottom: 8px;">' +
                    '无法初始化图表渲染引擎' +
                  '</div>' +
                  '<details style="margin-top: 8px;">' +
                    '<summary style="color: #c62828; cursor: pointer; font-size: 12px;">查看原始代码</summary>' +
                    '<pre style="background: #f8f9fa; padding: 8px; margin: 4px 0; border-radius: 2px; font-size: 11px; overflow-x: auto; white-space: pre-wrap;">' + content + '</pre>' +
                  '</details>' +
                '</div>';
              element.innerHTML = errorHtml;
            });
          });
        }
      </script>
    `;
  }
}
